/*
 * Copyright (c) 2023-2025 elsfs Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.elsfs.cloud.configuration;

import com.baomidou.dynamic.datasource.DynamicRoutingDataSource;
import javax.sql.DataSource;
import lombok.AllArgsConstructor;
import org.elsfs.cloud.api.security.key.OAuth2JWKRepository;
import org.elsfs.cloud.common.security.core.jwt.JdbcRsaKeyPairRepository;
import org.elsfs.cloud.module.dict.api.constant.DatasourceNameConstant;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.security.oauth2.server.authorization.JdbcOAuth2AuthorizationConsentService;
import org.springframework.security.oauth2.server.authorization.JdbcOAuth2AuthorizationService;
import org.springframework.security.oauth2.server.authorization.OAuth2AuthorizationConsentService;
import org.springframework.security.oauth2.server.authorization.OAuth2AuthorizationService;
import org.springframework.security.oauth2.server.authorization.client.RegisteredClientRepository;

/**
 * 配置授权数据源
 *
 * @author zeng
 */
@Configuration
@AllArgsConstructor
public class AuthDataSourceConfiguration {
  private final DataSource dataSource;
  private final RegisteredClientRepository registeredClientRepository;

  private JdbcTemplate getJdbcTemplate() {
    if (dataSource instanceof DynamicRoutingDataSource dynamicRoutingDataSource) {
      return new JdbcTemplate(
          dynamicRoutingDataSource.getDataSource(DatasourceNameConstant.OAUTH2));
    }
    return new JdbcTemplate(dataSource);
  }

  /**
   * Spring Security OAuth2 中用于处理授权同意逻辑的服务接口。它负责存储和检索用户的授权同意信息，确保用户在授权第三方应用访问其资源时的同意状态被正确记录。
   *
   * @return service
   */
  @Bean
  OAuth2AuthorizationConsentService oAuth2AuthorizationConsentService() {
    return new JdbcOAuth2AuthorizationConsentService(getJdbcTemplate(), registeredClientRepository);
  }

  @Bean
  OAuth2JWKRepository oAuth2JWKRepository() {
    JdbcRsaKeyPairRepository repository = new JdbcRsaKeyPairRepository(getJdbcTemplate());
    // repository.save(GenerateKeyUtils.getRsaKey());
    return repository;
  }

  /** 存储授权信息 认证之后的授权信息 */
  @Bean
  OAuth2AuthorizationService oAuth2AuthorizationService() {
    return new JdbcOAuth2AuthorizationService(getJdbcTemplate(), registeredClientRepository);
  }
}
